package amani.wechat.platform.core;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeewx.api.core.util.HttpRequestProxy;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import amani.wechat.platform.controller.model.WXUserInfo;
import amani.wechat.platform.services.ICommonService;
import amani.wechat.platform.utils.HttpRequestUtils;
import amani.wechat.platform.utils.WxUtils;

public class ContextModelActionInterceptor extends HandlerInterceptorAdapter {
	@Resource(name = "CommonService")
	ICommonService commonService;
	
	public static final String AUTH_URL="https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=connect_redirect#wechat_redirect";
	public static final String ACCESS_TOKEN="https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
	public static final String USER_INFO="https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//String openid = "obXNUs5la0QDIbYr7DfPWz28PK4k";
		//String openid	="orCjajg_JazaGkqIbNu2IgS4xjZQ";//
		try{
			String openid= HttpRequestUtils.GetCookieValue(request, "openid");
			if(StringUtils.isBlank(openid)){
				openid = ObjectUtils.toString(request.getSession().getAttribute("openid"));
			}
			//System.out.println("openid:"+openid);
			String currentUrlString=request.getRequestURL().toString();
			
			if(currentUrlString.endsWith("/ei/template") ||
			   currentUrlString.endsWith("/Orders/Step3") ||
			   currentUrlString.endsWith("/Orders/Step4") ||
			   currentUrlString.endsWith("/Orders/CommitOrder") ||
			   currentUrlString.contains("/system/") ||
			   currentUrlString.contains("/Success") ||
			   currentUrlString.contains("/UCenter/orders") ||
			   currentUrlString.endsWith("/index/wxapi") ||
			   currentUrlString.endsWith("/Pay/Notify")||
			   currentUrlString.endsWith("Card/Consume") || 
			   currentUrlString.endsWith("index/noneOpenid")|| 
			   currentUrlString.endsWith("/deposit") ||
			   currentUrlString.endsWith("/index/checkcard")||
			   currentUrlString.endsWith("/index/binding2")||
			   currentUrlString.endsWith("Orders/CommitOrder")){
				return true;
			}
			WXUserInfo userInfo=null;
			if(openid.equals("")){ 
				
				if(request.getParameter("state")!=null && request.getParameter("state").equals("connect_redirect")){ //验证重定向
					String code=request.getParameter("code");
					String requestUrl=String.format(ACCESS_TOKEN, WxUtils.GetAppId(),WxUtils.GetAppScrecte(),code);  
					String jsonResult= HttpRequestProxy.doGet(requestUrl, "UTF-8"); 
					JSONObject obj=JSONObject.fromObject(jsonResult);  
					if(obj.containsKey("errcode")&& obj.get("errcode").equals(40029)){
						if(request.getSession().getAttribute("openid")==null){
							//微信Auth
							String redectUrl= String.format(AUTH_URL, WxUtils.GetAppId(), java.net.URLEncoder.encode(currentUrlString, "UTF-8")); 
							response.sendRedirect(redectUrl);
							return false;
						}else{
							return true;
						}
					}
					userInfo=new WXUserInfo();
					if(obj.containsKey("openid")){
						userInfo.setOpenId(obj.getString("openid"));
					}else{
						response.sendRedirect(WxUtils.getWebsiteRoot()+"/index/noneOpenid");
						return false;
					}
					if(obj.containsKey("access_token")){
						userInfo.setUserAccessToken(obj.getString("access_token"));
					}else{
						response.sendRedirect(WxUtils.getWebsiteRoot()+"/index/noneOpenid");
						return false;
					}
					response.addCookie(new Cookie("openId", openid));
					//拉去用户信息
					requestUrl=String.format(USER_INFO, obj.getString("access_token"),obj.getString("openid")); 
					jsonResult= HttpRequestProxy.doGet(requestUrl, "UTF-8");
					obj=JSONObject.fromObject(jsonResult);  
					if(obj.containsKey("city")){
						userInfo.setCity(obj.getString("city"));
					}
					if(obj.containsKey("country")){
						userInfo.setCountry(obj.getString("country"));
					}
					if(obj.containsKey("headimgurl")){
						userInfo.setHeadimgurl(obj.getString("headimgurl"));
					}
					if(obj.containsKey("nickname")){
						userInfo.setNickName(obj.getString("nickname")); 
					}
					if(obj.containsKey("province")){
						userInfo.setProvince(obj.getString("province"));
					}
					if(obj.containsKey("sex")){
						userInfo.setSex(obj.getString("sex")); 
					} 
					request.getSession().setAttribute("userInfo", userInfo);  
					openid=userInfo.getOpenId();
				}else {
					//微信Auth
					String redectUrl= String.format(AUTH_URL, WxUtils.GetAppId(), java.net.URLEncoder.encode(currentUrlString, "UTF-8")); 
					response.sendRedirect(redectUrl);
					return false;
				} 
			} 
//			System.out.println("Cookie + openid:"+openid);
			response.addCookie(new Cookie("openid", openid));
	
			String tempOpenId = (String) request.getSession().getAttribute(
					"openid");
			if(tempOpenId==null){
				request.getSession().setAttribute("openid", openid); 
			}
			request.getSession().setAttribute("clientIp",HttpRequestUtils.getIpAddr(request));
			
			List<Map<String, Object>> meList=	commonService.loadMemberinfoByOpenid(openid);
			if(meList==null || meList.isEmpty()){
//				if (!currentUrlString.endsWith("Storefront/index/mf")&&
//						!currentUrlString.endsWith("Storefront/index/mr")&&
//						!currentUrlString.contains("/Storefront/")&&
//						!currentUrlString.contains("/CardTest/") &&
////						!currentUrlString.endsWith("/Storefront/worksByDesigner")&&
//						!currentUrlString.endsWith("/WxRequest")&&
//						!currentUrlString.endsWith("/SendCard")&&
//						!currentUrlString.endsWith("Pay/Notify")&&
//						!currentUrlString.endsWith("index/wxapi")&&
//						!currentUrlString.endsWith("/UCenter/index/binding")&&
//						!currentUrlString.endsWith("/UCenter/index/electronicCard")&&
//						!currentUrlString.endsWith("/UCenter/sendCard/send")&&
//						!currentUrlString.endsWith("/Shop/Index")	&&
//						!currentUrlString.endsWith("/Activity/Index")&&
//						!currentUrlString.endsWith("/Activity/Details")&&
//						!currentUrlString.endsWith("/UCenter/index/registElectronic")&&
//						!currentUrlString.endsWith("/UCenter/index/getmobilecode")&&
//						!currentUrlString.endsWith("/card/active")&&
//						!currentUrlString.endsWith("/deposit")) {///UCenter/index/registElectronic
//					response.sendRedirect(WxUtils.getWebsiteRoot()+"/UCenter/index/binding");
//					return false;
//				} 
				if( currentUrlString.endsWith("/Orders/Step1")||
						currentUrlString.endsWith("/UCenter/my")||
						currentUrlString.endsWith("/common/getCard")){
					response.sendRedirect(WxUtils.getWebsiteRoot()+"/UCenter/index/binding");
					return false;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return true;

	}

	

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if(modelAndView==null){  
			super.postHandle(request, response, handler, modelAndView);
			return;
		}else  {
			String path = request.getContextPath() + "/";
			String hostPath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ path;
			modelAndView.addObject("ROOT_PATH", path);
			modelAndView.addObject("HOST_PATH", hostPath);
		String url= request.getScheme() + "://"
				+ request.getServerName() +  request.getContextPath()+request.getServletPath();
		String queryString = request.getQueryString();
		if(queryString!=null&&queryString.length()>0){
			url = url + "?" + queryString;
		}
		Map<String, String> map = WxUtils.JssdkSign(url);
		
		modelAndView.addObject("appId", WxUtils.GetAppId());
		modelAndView.addObject("jsapi_timestamp", map.get("timestamp"));
		modelAndView.addObject("jsapi_nonceStr", map.get("nonceStr"));
		modelAndView.addObject("jsapi_signature", map.get("signature"));

		String openid =(String) request.getSession().getAttribute(
				"openid");
		modelAndView.addObject("openid", openid);

		String cardno = (String) request.getSession().getAttribute(
				"currentusercardno");
		String membername = (String) request.getSession().getAttribute(
				"currentmembername");
		String membermphone = (String) request.getSession().getAttribute(
				"currentmembermphone");
		if (cardno == null || membername == null || membermphone == null) {
			List<Map<String, Object>> maplist = commonService
					.loadMemberinfoByOpenid(openid);
			if(maplist.size()>0){
				cardno = (String) maplist.get(0).get("cardno");
				membername = (String) maplist.get(0).get("membername");
				membermphone = (String) maplist.get(0).get("membermphone");
				request.getSession().setAttribute("openid", openid);
				request.getSession().setAttribute("currentmemberno", "cardno");
				request.getSession()
						.setAttribute("currentmembername", "membername");
				request.getSession().setAttribute("currentmembermphone",
						"membermphone");
			}
		}

		modelAndView.addObject("currentusercardno", cardno);
		modelAndView.addObject("currentmembername", membername);
		modelAndView.addObject("currentmembermphone", membermphone);

		super.postHandle(request, response, handler, modelAndView);
		}
	}
}
